package org.freedoit.server.service.auth;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freedoit.server.dao.DAOFactory;
import org.freedoit.server.om.User;
import org.freedoit.server.service.data.AuthReturnResult;
import org.freedoit.server.service.data.ReturnResult;
import org.freedoit.shared.util.Constants;

import com.google.gson.Gson;

public class AuthServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1906298542516433980L;
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		String user = request.getParameter("user");
		if (user == null || "".equals(user)) {
			response.getWriter().write(new Gson().toJson(new AuthReturnResult(ReturnResult.CODE_INVALID_REQUEST), 
					new com.google.gson.reflect.TypeToken<AuthReturnResult>() {}.getType()));
			
			return;
		}

		String key = request.getParameter("key");
		if (key == null || "".equals(key)) {
			response.getWriter().write(new Gson().toJson(new AuthReturnResult(ReturnResult.CODE_INVALID_REQUEST), 
					new com.google.gson.reflect.TypeToken<AuthReturnResult>() {}.getType()));
			
			return;
		}
		
		User userExisted = DAOFactory.getUserDAO().findByUserName(user);
		if (userExisted == null) {
			response.getWriter().write(new Gson().toJson(new AuthReturnResult(ReturnResult.CODE_USER_NOT_EXIST), 
					new com.google.gson.reflect.TypeToken<AuthReturnResult>() {}.getType()));
			
			return;
		}
		
		if (key.equals(userExisted.getUserKey())) {
			// 
			request.getSession().setAttribute(Constants.DOIT_USER_KEY, userExisted);
			AuthReturnResult arr = new AuthReturnResult(ReturnResult.CODE_OK);
			arr.setUserId(userExisted.getUserId());
			response.getWriter().write(new Gson().toJson(arr, 
					new com.google.gson.reflect.TypeToken<AuthReturnResult>() {}.getType()));
		} else {
			response.getWriter().write(new Gson().toJson(new AuthReturnResult(ReturnResult.CODE_AUTH_FAILURE), 
					new com.google.gson.reflect.TypeToken<AuthReturnResult>() {}.getType()));
		}
	}

}
